package io.hellsinger.filesystem

import io.hellsinger.filesystem.path.Path
import io.hellsinger.filesystem.path.PathOwner
import java.nio.charset.Charset

fun <P : Path> P.checkScheme(scheme: Int) {
    check(this.scheme == scheme) { "Invalid scheme ${this.scheme}" }
}

fun <P : Path> P.checkScheme(
    scheme: Int,
    lazyMessage: () -> Any,
) {
    check(
        value = this.scheme == scheme,
        lazyMessage = lazyMessage,
    )
}

fun <P : Path> PathOwner<P>.checkScheme(scheme: Int) {
    path.checkScheme(scheme)
}

fun <P : Path> PathOwner<P>.checkScheme(
    scheme: Int,
    lazyMessage: () -> Any,
) {
    path.checkScheme(scheme, lazyMessage)
}

class ByteArrayBuilder(
    capacity: Int,
) {
    private var data = ByteArray(capacity)
    private var index = 0

    fun append(byte: Byte) {
        if (index + 1 > data.size) copyWithNewSize(2 * data.size)

        data[index++] = byte
    }

    fun isEmpty() = data.isEmpty()

    fun isNotEmpty() = !isEmpty()

    private fun copyWithNewSize(size: Int) {
        data = data.copyOf(size)
    }

    fun toString(charset: Charset): String = String(data, charset)

    fun build(): ByteArray = data.copyOf()

    fun reset() {
        data = ByteArray(data.size)
        index = 0
    }
}
